package com.wzg.appframe.web.jsbridge;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.WebView;

import com.google.gson.JsonObject;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;
import com.wzg.appframe.action.WebAction;
import com.wzg.appframe.utils.GsonUtil;
import com.wzg.appframe.utils.TLog;
import com.wzg.appframe.utils.ToastUtil;
import com.wzg.appframe.web.BaseWebActivity;
import com.wzg.gprintlib.Constant;
import com.wzg.gprintlib.GPrintLib;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by youliang.ji on 2016/12/23.
 */

public class JavaSctiptMethods {
    private WebView webView;
    private Activity mActivity;
    private WebAction webAction;
    private GPrintLib gPrintLib;

    public JavaSctiptMethods(Activity mContext, WebView webView) {
        this.mActivity = mContext;
        this.webView = webView;
        this.webAction = new WebAction(mContext, this);
        gPrintLib = new GPrintLib(mContext);
    }

    /**
     * 统一分发js调用android分发
     */
    public void send(String[] jsons) {
        final String str = jsons[0];
        TLog.d("json=" + str);
        try {
            JSONObject json = new JSONObject(str);
            String action = json.optString("action");//js传递过来的动作，比如callPhone代表拨号，share2QQ代表分享到QQ，其实就是H5和android通信协议（自定义的）
            if (!TextUtils.isEmpty(action)) {
                if ("toast".equals(action)) {
                    toast(str);
                } else if ("openNewPage".equals(action)) {
                    openNewPage(str);
                } else if ("scanCode".equals(action)) {
                    scanCode(str);
                } else if ("closePage".equals(action)) {
                    closePage();
                } else if ("log".equals(action)) {
                    log(str);
                } else if ("getLocalData".equals(action)) {
                    getLocalData(str);
                } else if ("printConn".equals(action)) {
                    printConn(str);
                } else if ("print".equals(action)) {
                    print(str);
                } else if ("getPrintStatus".equals(action)) {
                    getPrintStatus(str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    //======================打印 API =================================

    /**
     * 连接打印机
     */
    public void printConn(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            commCallBack = jsonObject.optString("callback");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        gPrintLib.bluetoothConn(mActivity);
    }

    public void print(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String printContent = jsonObject.optString("printContent");
            gPrintLib.startPrint(printContent);
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

    public void getPrintStatus(String json) throws JSONException {
        JSONObject jObj = new JSONObject(json);
        String callback = jObj.optString("callback");
        JsonObject jsonObject = new JsonObject();

        String statusInfo = gPrintLib.getStatusInfo();
        jsonObject.addProperty("result", statusInfo);
        String str = GsonUtil.obj2String(jsonObject);

        invokeJavaScript(callback, str);
    }

    //======================打印 API =================================

    public void getLocalData(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            commCallBack = jsonObject.optString("callback");
            Map<String,?>map = webAction.getAll();
            String mapStr = GsonUtil.obj2String(map);
            commBack(mapStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void log(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String logData = jsonObject.optString("logData");
            TLog.d(logData);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 提示
     *
     * @param json
     */
    private void toast(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String msg = jsonObject.optString("msg");
            ToastUtil.show(msg);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 打开新界面
     *
     * @param str
     * @throws JSONException
     */
    private void openNewPage(String str) throws JSONException {
        JSONObject mJson = new JSONObject(str);
        String pageUrl = mJson.optString("pageUrl");
        Intent intent = new Intent(this.mActivity, BaseWebActivity.class);
        intent.putExtra(BaseWebActivity.PAGE, pageUrl);
        this.mActivity.startActivity(intent);
    }

    /**
     * 关闭界面
     */
    private void closePage() {
        this.mActivity.finish();
    }


    /**
     * 扫描跳转Activity RequestCode
     */
    public static final int REQUEST_CODE = 1001;
    String commCallBack;

    /**
     * 扫码api
     *
     * @param json
     * @throws JSONException
     */
    private void scanCode(String json) throws JSONException {
        JSONObject jsonObject = new JSONObject(json);
        commCallBack = jsonObject.optString("callback");
        Intent intent = new Intent(this.mActivity, CaptureActivity.class);
        this.mActivity.startActivityForResult(intent, REQUEST_CODE);
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        TLog.d("!@#123 requestCode=" + requestCode);
        /**
         * 处理二维码扫描结果
         */
        if (requestCode == REQUEST_CODE) {
            //处理扫描结果（在界面上显示）
            if (null != data) {
                Bundle bundle = data.getExtras();
                if (bundle == null) {
                    return;
                }
                if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_SUCCESS) {
                    String result = bundle.getString(CodeUtils.RESULT_STRING);
                    commBack(result);
                } else if (bundle.getInt(CodeUtils.RESULT_TYPE) == CodeUtils.RESULT_FAILED) {
                    ToastUtil.show("解析二维码失败");
                }
            }
        } else if (requestCode == Constant.BLUETOOTH_REQUEST_CODE) {
            TLog.d("2222");
            gPrintLib.onActivityResult(requestCode, resultCode, data);

            gPrintLib.setCallBack(new GPrintLib.callBack() {
                @Override
                public void onConect(int state, String connInfo) {

                    commBack(connInfo);
                }
            });

        }

    }

    public void onStart() {
        gPrintLib.onStart(mActivity);
    }

    public void onDestroy() {
        gPrintLib.onDestroy(mActivity);
    }

    public void onStop() {
        gPrintLib.onStop(mActivity);
    }

    private void commBack(String result) {
        TLog.d("commBack=" + result);
        if (null != commCallBack && !"".equals(commCallBack)) {
            try {
//                JSONObject resultJosn = new JSONObject(result);
                JSONObject json = new JSONObject();
                json.put("result", result);
                invokeJavaScript(commCallBack, json.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 统一管理所有android调用js方法
     *
     * @param callback js回调方法名
     * @param json     传递json数据
     */
    private void invokeJavaScript(final String callback, final String json) {
        if (TextUtils.isEmpty(callback)) return;
        //调用js方法必须在主线程
        webView.post(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:" + callback + "(" + json + ")");
            }
        });
    }

    /**
     * 统一管理所有android调用js方法
     *
     * @param callback     js回调方法名
     * @param responseJson 传递json数据
     */
    public void invokeJavaScript(final String callback, final String methodName, final String responseJson) {

        if (TextUtils.isEmpty(callback)) return;
        //调用js方法必须在主线程
        webView.post(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl("javascript:" + callback + "('" + methodName + "'," + responseJson + ")");
            }
        });
    }

}
